<template>
    <div class="detail_main" v-if="item.id > 0">
      <div class="__main_left">
        <div class="img">
          <img :src="item.image_url" style="width: 100%"/>
        </div>
        <div class="properties">
          <div class="properties_1">
            <div>
              <img src="@/assets/Properties.png" alt="">
            </div>
            <div>Properties</div>
          </div>
          <div class="properties_2">
            <div class="_warp_list" v-for="(item,index) in propertiesData">
              <div :class="`div_img${index}`"></div>
              <div class="div_txt">{{item.txt}}</div>
              <div class="div_name">{{item.name}}</div>
            </div>
            <div v-show="isMobile" class="_warp_list_placeholder"></div>
          </div>
        </div>
        <div class="properties">
          <div class="properties_1">
            <div>
              <img src="@/assets/Details.png" alt="">
            </div>
            <div>Details</div>
          </div>
          <div class="properties_11">
              <div class="_p_11_list">
                <span>Contract Address</span>
                <span>{{ item.nft_address.substr(0,4) + '...' + item.nft_address.substr(40) }}</span>
              </div>
            <div class="_p_11_list">
              <span>Token ID</span>
              <span>{{ item.token_id }}</span>
            </div>
            <div class="_p_11_list">
              <span>Token Standard</span>
              <span>{{ item.token_standard }}</span>
            </div>
            <div class="_p_11_list">
              <span>Blockchain</span>
              <span>Binance Smart Chain</span>
            </div>
          </div>
        </div>
      </div>
      <div class="__main_right">
        <div class="__main_right_title">{{ item.name }} #{{item.num}}</div>
<!--        <div class="_home_name1">-->
<!--          <div></div>-->
<!--          <div>MGC</div>-->
<!--        </div>-->
        <div v-if="true" class="_home_details">
          <div class="_home_details_1">
            <div class="_home_details_l" style="">
              <div class="_de_txt">Fixed price</div>
              <div style="display: flex;align-items: center;margin-top: 5px">
<!--                <div class="_de_icon"></div>-->
                <div class="_de_rmb">{{ fromWei(item.fixed_price) }}</div>
              </div>
              <div class="_de_thr">
                <span>Total price:</span>
                <span>{{ fromWei(item.total_price) }} {{ item.unit }}</span>
              </div>
            </div>
            <div class="_home_details_r" style="">
              <div class="_de_txt">Count</div>
              <span>{{ item.count }}</span>
            </div>
          </div>
          <div v-if="item.status === 'sell' && item.owner.toLowerCase() !== state.address.toLowerCase()" class="_home_details_2" @click="showBuyConfirm">Buy Now</div>
          <div v-if="item.status === 'sell' && item.owner.toLowerCase() === state.address.toLowerCase()" class="_home_details_2" @click="onRevoke">Revoke</div>
          <div v-if="item.status === 'success' || item.status === 'cancel'" class="_home_details_3">Sold out</div>
        </div>
        <div v-if="false" class="_home_details">
          <div class="_count">count</div>
          <div class="_count_num">1</div>
          <div class="_count_btns">
            <div class="sell">Sell</div>
            <div class="transfer">Transfer</div>
          </div>
        </div>
        <div class="properties properties-right">
          <div class="properties_3">
            <div>Description</div>
          </div>
          <div class="properties_4">{{ item.description }}</div>
        </div>
      </div>
    </div>

  <Dialog v-if="s.loading" title="Wait" :close="close"></Dialog>
  <Dialog v-if="s.showBuyConfirm" title="Buy Now" :item="item" :allow="s.allow" :close="close" :buy="onBuy" :approve="onApprove"></Dialog>

</template>

<script setup>
import Dialog from '@/components/Dialog/Dialog.vue'
import http from "../../http";
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import {allowance, approve, buy, cancelSell, comp, getAddress, getBalance, mul, state, watch} from "../../dapp";

const propertiesData = ref([])
  const router = useRouter()

  const route = useRoute()

  const item = ref({})
  const s = ref({
    loading: false,
    showBuyConfirm: false,
    allow: false,
  })

  function close() {
    s.value.loading = false
    s.value.showBuyConfirm = false
  }

  async function onApprove() {
    if (!s.value.allow) {
      if (submit) {
        return
      }
      submit = true

      console.log('onApprove====')

      try {
        const current = item.value
        const address = await getAddress()
        console.log('approve', current)
        const curr = current.currency
        if (curr !== '0x0000000000000000000000000000000000000000') {
          var balance = await getBalance(curr, address)
          console.log('balance=', balance)
          // if (balance < current.total_price*current.count) {
          // console.log('total=',current.fixed_price,current.total_price, current.count, mul(current.total_price, current.count).toFixed(0))
          if (comp(balance, current.total_price) < 0) {
            Toast('Insufficient available')
            throw new Error('Insufficient available')
            // return
          }

          var allowBalance = await allowance(curr, address, current.type)
          console.log('allowBalance=', allowBalance, allowBalance < current.total_price)
          // if (allowBalance < current.total_price*current.count) {
          if (comp(allowBalance, current.total_price) < 0) {
            // var value = '0x' + (current.total_price*current.count).toString(16)
            var value = '0x' + mul(current.total_price, '1').toString(16)
            console.log('approve', value)
            var tt = await approve(curr, value, current.type)
            console.log('approve hash=', tt)
            console.log('wait')
            s.value.loading = true
            await watch(tt)
            s.value.showBuyConfirm=false
            s.value.allow = true
            s.value.showBuyConfirm=true
            console.log('approve success')
          } else {
            // s.value.showBuyConfirm=false
            s.value.allow = true
            // s.value.showBuyConfirm=true
          }
        }

      } catch (e) {
        console.log('err=', e)
        if (e.message.indexOf('cant buy from yourself') !== -1) {
          Toast('Cant buy from yourself')
        } else if (e.message.indexOf('sold or canceled') !== -1) {
          Toast('Seller canceled')
        }
      }

      submit = false
      s.value.loading = false
    }
  }

  async function init() {
    var id = route.query.id
    if (id && id > 0) {
      var res = await http.get(`/api/nft-sales/${id}`)
      item.value = res.data
      checkAllow()
      if (res.data.properties) {
        var propMap = {}
        res.data.properties.map(row => {
          propMap[row.trait_type] = row.value
        })

        propertiesData.value = [
          {
            name:propMap['star'],
            txt:'Rarity ',
            img:'div_img0'
          },
          {
            name:propMap['rank'],
            txt:'Rank  ',
            img:'div_img1'
          },
          {
            name:propMap['level'],
            txt:'Level  ',
            img:'div_img2'
          },
          {
            name:propMap['Property'],
            txt:'Property  ',
            img:'div_img3'
          },
          {
            name:propMap['score'],
            txt:'Score ',
            img:'div_img4'
          },
        ]
      }
    }

  }

  async function checkAllow() {
    try {
      const current = item.value
      console.log('showBuyConfirm', current)
      const curr = current.currency
      if (curr !== '0x0000000000000000000000000000000000000000') {
        const address = await getAddress()
        var balance = await getBalance(curr, address)
        console.log('balance=', balance)
        if (balance < current.total_price*1) {
          return
        }
        var allowBalance = await allowance(curr, address, current.type)
        console.log('allowBalance=', allowBalance)
        // if (allowBalance < current.total_price*1) {
        if (comp(allowBalance, mul(current.total_price, '1')) < 0) {
          return
        }
        s.value.allow = true
        console.log('allow==', s.value.allow)
      } else {
        s.value.allow = true
      }
    } catch (e) {
      console.log('err=', e)
    }
  }

  var submit = false

  async function showBuyConfirm() {
    s.value.showBuyConfirm=true
  }

  async function onBuy() {
    if (!s.value.allow) {
      return
    }
    if (submit) {
      return
    }
    submit = true

    try {
      const current = item.value
      const address = await getAddress()
      console.log('buy', current)
      const curr = current.currency
      var price = current.total_price
      if (curr !== '0x0000000000000000000000000000000000000000') {
        price = 0
        var balance = await getBalance(curr, address)
        console.log('balance=', balance)
        if (comp(balance, mul(current.total_price, '1')) < 0) {
        // if (balance < current.total_price*1) {
          Toast('Insufficient available')
          return
        }
        var allowBalance = await allowance(curr, address, current.type)
        console.log('allowBalance=', allowBalance)
        // if (allowBalance < current.total_price*1) {
        //   var value = '0x' + (current.total_price*1).toString(16)

        if (comp(allowBalance, mul(current.total_price, '1')) < 0) {
          var value = '0x' + mul(current.total_price, '1').toString(16)

          console.log('approve', value)
          var tt = await approve(curr, value, current.type)
          console.log('approve hash=', tt)
          console.log('wait')
          s.value.loading = true
          await watch(tt)
          console.log('approve success')
        }
      }
      var iserc = current.token_standard === "BEP20"
      var txid = await buy(current.id, curr, iserc ? 1 : 0, price, current.type)
      // Toast('Submit')
      console.log('res=', txid)
      console.log('wait tx confirm')
      s.value.loading = true
      await watch(txid)
      await http.get(`/api/sync?txid=${txid}`)
      console.log('tx was confirm')
      init()
    } catch (e) {
      console.log('err=', e)
      if (e.message.indexOf('cant buy from yourself') !== -1) {
        Toast('Cant buy from yourself')
      } else if (e.message.indexOf('sold or canceled') !== -1) {
        Toast('Seller canceled')
      }
    }

    s.value.showBuyConfirm=false
    submit = false
    s.value.loading = false
    // 返回上一页
    router.back();
  }

  async function onRevoke() {
    if (submit) {
      return
    }
    submit = true
    try {
      const current = item.value
      console.log('revoke', current)
      var txid = await cancelSell(current.id, current.token_standard === "BEP20" ? 1 : 0, current.type)
      console.log('txid=', txid)
      // Toast('Submit')
      console.log('wait tx confirm')
      s.value.loading = true
      await watch(txid)
      await http.get(`/api/sync?txid=${txid}`)
      console.log('tx was confirm')
      init()
    } catch (e) {
      console.log('err=', e)
      if (e.message.indexOf('cant buy from yourself') !== -1) {
        Toast('Cant buy from yourself')
      } else if (e.message.indexOf('sold or canceled') !== -1) {
        Toast('Seller canceled')
      }
    }
    submit = false
    s.value.loading = false
    // 返回上一页  
    router.back();
  }

  init()

</script>

<script>
export default {
  data() {
    return {
      isMobile: document.body.clientWidth <= 750
    }
  }
}
</script>

<style scoped lang="scss">
  .detail_main {
    margin-top: 176px;
    padding-left: 74px;
    display: flex;
    /*align-items: center;*/
  }
  .__main_left {
      .img {
        width: 530px;
        height: 530px;
        border: 1px solid #D9D9D9;
        /*background-color: #F0D38B;*/
      }
  }
  .properties {
    margin-top: 22px;
    width: 526px;
    /*width: 676px;*/
    /*height: 128px;*/
    border: 1px solid #D9D9D9;
  }
  .properties-right {
    width: 676px;
  }
  .properties_1 {
    padding: 28px 23px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;
    div {
      &:nth-child(1) {
        width: 24px;
        height: 22px;
        /*background-color: pink;*/
      }
       img {
         width: 24px;
         height: 22px;
         display: inherit;
       }
      &:nth-child(2) {
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #AFAFAF;
        margin-left: 25px;
      }
    }
  }
  .__main_right {
    margin-left: 25px;
  }
  ._home_name1 {
    margin-top: 22px;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    div {
      &:nth-child(1) {
        border-radius: 50%;
        width: 38px;
        height: 38px;
        background: url("@/assets/logo1.png") no-repeat center;
        background-size: cover;
      }

      &:nth-child(2) {
        font-size: 18px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #383838;
        margin-left: 8px;
      }
    }
  }
  .__main_right_title {
    font-size: 40px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
  }
  ._home_details {
    width: 677px;
    /*height: 209px;*/
    border: 1px solid #D9D9D9;
    margin-top: 33px;
    padding: 26px 16px;
  }
  ._home_details_1 {
    display: flex;
    align-items: center;
    padding-right: 24px;

  }
  ._de_txt {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #383838;
  }
  ._de_rmb {
    font-size: 28px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
    margin-left: 5px;
  }
  ._de_icon {
    width: 30px;
    height: 16px;
    background: url("@/assets/c1.png") no-repeat center;
    background-size: cover;
  }
  ._de_thr {
    font-size: 14px;
    span {
      &:nth-child(1) {
        color: #AFAFAF;
      }
      &:nth-child(2) {
        color: #383838;
      }
    }
  }
  ._home_details_l {
    width: 366px;border-right: 1px solid #D9D9D9
  }
  ._home_details_r {
    padding-left: 25px;
    font-size: 28px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
  }
  ._home_details_2 {
    width: 342px;
    height: 48px;
    background: #FEC434;
    font-size: 16px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
    line-height: 48px;
    margin-top: 15px;
    text-align: center;
    cursor: pointer;
  }
  .properties_3 {
    padding: 23px 23px 18px 23px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #979797;;
    div {
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #AFAFAF;
    }
  }
  .properties_4 {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #AFAFAF;
    padding: 23px;
  }
  ._count {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #383838;
  }
  ._count_num {
    font-size: 28px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
    padding-left: 76px;
    margin-top: 15px;
  }
  ._count_btns {
    display: flex;
    margin-top: 10px;
    >div {
      width: 240px;
      height: 48px;
      background: #FEC434;
      margin-right: 24px;
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #393939;
      line-height: 48px;
      text-align: center;
    }
  }
  ._home_details_3 {
    width: 342px;
    height: 48px;
    background: #F4F4F4;
    font-size: 16px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #393939;
    line-height: 48px;
    margin-top: 15px;
    text-align: center;
  }
  @media screen and (max-width: 750px) {
    ._home_details_3 {
      width: 100%;
    }
  }
  .loading_box {
    width: 12px;
    height: 12px;
  }
  .properties_2 {
    padding: 19px 24px 33px 25px;
    @include flex;
    display: flex;
    flex-direction: row;
    overflow-x: auto;
    .div_img {

    }
    .div_txt {
      font-size: 12px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #393939;
      margin-top: 3px;
    }
    .div_name {
      font-size: 18px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #393939;
      margin-top: 4px;
    }
  }
  ._warp_list {
    width: 88px;
    height: 100px;
    border: 1px solid #EBEBEB;
    text-align: center;
  }
  ._warp_list_placeholder {
    width: 88px;
    height: 100px;
  }
  .div_img0 {
    background: url("@/assets/d1.png") no-repeat center;
    background-size: cover;
    width: 27px;
    height: 23px;
    margin: 16px auto 0;
  }
  .div_img1 {
    background: url("@/assets/d2.png") no-repeat center;
    background-size: cover;
    width: 22px;
    height: 27px;
    margin: 13px auto 0;
  }
  .div_img2 {
    background: url("@/assets/d3.png") no-repeat center;
    background-size: cover;
    width: 26px;
    height: 27px;
    margin: 13px auto 0;
  }
  .div_img3 {
    background: url("@/assets/d4.png") no-repeat center;
    background-size: cover;
    width: 25px;
    height: 24px;
    margin: 18px auto 0;
  }
  .div_img4 {
    background: url("@/assets/d5.png") no-repeat center;
    background-size: cover;
    width: 26px;
    height: 26px;
    margin: 14px auto 0;
  }
  .properties_11 {
    padding: 23px 25px;
  }
  ._p_11_list {
    @include flex;
    margin-top: 16px;
    height: 20px;
    &:nth-child(1) {
      margin-top: 0;
    }
    span {
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      &:nth-child(1) {

        color: #888888;
      }
      &:nth-child(2) {
        color: #383838;
      }
    }
  }

  @media screen and (max-width: 750px) {
    .detail_main {
      flex-direction: column;
      margin-top: 20px;
      padding-left: 0;
    }
    .__main_left {
      flex: 1;
      .img {
        width: 100%;
        height: 100%;
        border: 1px solid #D9D9D9;
        /*background-color: #F0D38B;*/
      }
    }
    .__main_right{
      flex: 1;
      margin-left: 0;
    }
  .properties {
    width: 100%;
  }
    .properties_1 {
      padding: 23px 25px;
    }
    ._home_details{
      width: 100%;
    }
    ._home_details_2 {
      width: 100%;
    }
  }

  .properties_2 {
    overflow-y: scroll;
    flex-wrap: wrap;
    // justify-content: start;
  }
  ._warp_list {
    width: 88px;
    height: 100px;
    border: 1px solid #EBEBEB;
    text-align: center;
    margin-top: 15px;
  }

</style>
